package com.itlong.cloud.iot.alibaba.mns.polling;

import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.model.Message;
import com.itlong.cloud.POJO.DTO.common.HandleResultDTO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.iot.alibaba.util.AliClient;
import com.itlong.cloud.iot.alibaba.mns.CloudQueueMessageReceiver;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.utils.node.JsonUtil;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <desc>
 *      Iot 群控器获取呼梯结果轮询类
 * </desc>
 *
 * @createDate 2018/04/10
 */
@Service
@RefreshScope
public class IotHandleResultPolling {
    private static final Logger LOG = LoggerFactory.getLogger(IotHandleResultPolling.class);
    protected static MNSClient sMNSClient;
    @Autowired
    RedisService redisService;
    @Autowired
    MessageSender messageSender;
    @Autowired
    AliClient aliClient;
    @Value("${" + PlatformConstants.MNSEndpoint + "}")
    private  String endpoint;    //消息服务Endpoint
    @Value("${" + PlatformConstants.IOT_CLOUD_HANDLE_RESULT_QUEUE + "}")
    private  String QueueName;  //队列名
    private ExecutorService cachedThreadPool ; //线程池


    /**
     * <desc>
     *      线程开始轮询
     * </desc>
     *
     * @param workerId
     * @author Jiaqi.X
     * @createDate 2018/04/10
     */
    public void worker(int workerId) {
        CloudQueueMessageReceiver receiver = new CloudQueueMessageReceiver(workerId, sMNSClient, QueueName);
        while (true) {
            Message message = receiver.receiveMessage();
            //读取到设备上传的状态数据，并设置缓存
            try {
                LOG.info(String.format("【iot设备控制指令结果上报数据】：%s",message.getMessageBodyAsBase64()));
                HandleResultDTO dto = JsonUtil.toObject(message.getMessageBodyAsBase64(), HandleResultDTO.class);
                //设置缓存(时间戳毫秒数也放在键里面没意义)
                //redisService.set(RedisConstant.REDIS_IOT_DEVICE_HANDLE_RESULT_CACHE +
                                //dto.getSnr() + "_" + message.getFirstDequeueTime().getTime(),
                        //RedisConstant.REDIS_IOT_DEVICE_HANDLE_RESULT_CACHE_TIME, dto);
                //设置缓存
                redisService.set(RedisConstant.REDIS_IOT_DEVICE_HANDLE_RESULT_CACHE + "_ali_" + dto.getSnr(), RedisConstant.REDIS_IOT_DEVICE_HANDLE_RESULT_CACHE_TIME, dto);
            } catch (Exception e) {
                LOG.error("【MNS获取iot设备控制指令结果上报数据异常】" + e.getMessage());
            } finally {
                //处理完后删除队列消息
                sMNSClient.getQueueRef(QueueName).deleteMessage(message.getReceiptHandle());
            }
        }
    }

    /**
     * <desc>
     *      初始化
     * </desc>
     *
     * @author Jiaqi.X
     * @createDate 2018/04/10
     */
    @PostConstruct
    public void polling(){
        //初始化线程池
        cachedThreadPool = Executors.newFixedThreadPool(10);
        CloudAccount account = aliClient.getCloudAccount(endpoint);
        sMNSClient = account.getMNSClient();
        //开启10个线程读取消息
        for(int i=1;i<=10;i++){
            int id=i;
            cachedThreadPool.execute(() -> {
                worker(id);
            });
        }
    }
}
